package com.example.common.base;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import androidx.appcompat.app.AppCompatActivity;

import com.example.common.utils.CustomToastUtil;
import com.example.common.utils.StatusBar.StatusBarUtil;

/**
 * @author skygge
 * @date 2020/7/30.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：activity基类
 */
public class BaseActivity extends AppCompatActivity {
    protected String TAG = getClass().getSimpleName();
    protected Context mContext;
    protected Handler mHandler;

    private BaseLoadingDialog mDialog;

    /**
     * 获取Layout
     */
    protected int getLayoutId(){
        return -1;
    }

    protected void initialization(){
        immersionStatusBar(true);
        mContext = this;
        mHandler = new Handler();
        initialize();
        bindPresent();
        initView();
        initData();
        initListener();
        initDataBus();
    }

    /**
     * 初始化
     */
    protected void initialize() {
    }

    /**
     * 绑定present
     */
    protected void bindPresent(){

    }

    /**
     * 初始化控件
     */
    protected void initView() {
    }

    /**
     * 初始化数据
     */
    protected void initData() {
    }

    /**
     * 通信消息
     */
    protected void initDataBus() {
    }

    /**
     * 监听事件写在这
     */
    protected void initListener() {
    }


    /**
     * 沉浸式导航栏
     * @param isDark 深色浅色切换
     */
    protected void immersionStatusBar(boolean isDark){
        StatusBarUtil.setRootViewFitsSystemWindows(this,true);
        StatusBarUtil.setTranslucentStatus(this);
        if (!StatusBarUtil.setStatusBarDarkTheme(this, isDark)) {
            StatusBarUtil.setStatusBarColor(this,0x55000000);
        }
    }

    protected void skipAnotherActivity(Class<?> mClass){
        startActivity(new Intent(mContext, mClass));
    }

    protected void skipAnotherActivity(Bundle bundle, Class<?> clazz) {
        Intent intent = new Intent(mContext, clazz);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    protected void showToast(String content) {
        CustomToastUtil.showToast(mContext, content);
    }

    protected void showToast(int strRes) {
        CustomToastUtil.showToast(mContext, strRes);
    }

    protected void showProgressDialog() {
        if (mDialog == null){
            mDialog = new BaseLoadingDialog(mContext);
            mDialog.show();
            mHandler.postDelayed(mRunnable, 5000);
        }
    }

    protected void showProgressDialog(boolean enable) {
        if (mDialog == null){
            mDialog = new BaseLoadingDialog(mContext);
            mDialog.show();
            if (enable){
                mHandler.postDelayed(mRunnable, 5000);
            }
        }
    }

    protected void dismissProgressDialog() {
        mHandler.post(mRunnable);
    }

    private Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            if (mDialog!=null){
                mDialog.dismiss();
                mDialog = null;
            }
        }
    };

    /**
     * 隐藏软键盘
     */
    protected void hideSoftKeyboard() {
        InputMethodManager inputMethodManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
        if(inputMethodManager != null ) {
            View localView = this.getCurrentFocus();
            if(localView != null && localView.getWindowToken() != null ) {
                IBinder windowToken = localView.getWindowToken();
                inputMethodManager.hideSoftInputFromWindow(windowToken, 0);
            }
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {  //把操作放在用户点击的时候
            View v = getCurrentFocus();      //得到当前页面的焦点,ps:有输入框的页面焦点一般会被输入框占据
            if (isShouldHideKeyboard(v, ev)) { //判断用户点击的是否是输入框以外的区域
                if (v.getWindowToken() != null) {//收起键盘
                    InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (im!=null) {
                        im.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    }
                }
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时则不能隐藏
     */
    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if ((v instanceof EditText)) {  //判断得到的焦点控件是否包含EditText
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0],    //得到输入框在屏幕中上下左右的位置
                    top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            // 点击位置如果是EditText的区域，忽略它，不收起键盘。
            return !(event.getX() > left) || !(event.getX() < right)
                    || !(event.getY() > top) || !(event.getY() < bottom);
        }
        // 如果焦点不是EditText则忽略
        return false;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK &&event.getRepeatCount() ==0){
            dismissProgressDialog();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacks(mRunnable);
        mHandler.removeCallbacksAndMessages(null);
    }
}
